package com.lagou.edu.controller;

import com.lagou.edu.service.CodeService;
import com.lagou.edu.service.TokenService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private CodeService codeService;

    @Autowired
    private TokenService tokenService;

    /**
     * 用户注册
     *
     * @param email
     * @param password
     * @param code
     * @param response
     * @return
     */
    @RequestMapping("/register/{email}/{password}/{code}")
    public int register(@PathVariable(value = "email") String email, @PathVariable(value = "password") String password, @PathVariable("code") String code, HttpServletResponse response) {
        // 调用验证码服务验证是否正确
        int result = codeService.validateCode(email, code);
        if (result == 0) {
            tokenService.register(email, password);
        }
        return result;
    }

    /**
     * 用户是否注册过
     *
     * @param email
     * @return
     */
    @RequestMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email) {
        return tokenService.isRegistered(email);
    }

    /**
     * 用户登录
     * @param email
     * @param password
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login/{email}/{password}")
    public String login(@PathVariable(value = "email") String email, @PathVariable(value = "password") String password, HttpServletRequest request, HttpServletResponse response) {

        // 验证用户名密码
        boolean validate = tokenService.validate(email, password);

        if (validate) {
            String token = tokenService.createToken(email, password);
//            tokenService.saveToken(email, token);

            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);

            return email;
        } else {
            return "false";
        }

    }

    /**
     * 根据token获取邮件地址
     *
     * @param token
     * @return
     */
    @RequestMapping("/info/{token}")
    public String info(@PathVariable String token) {

        String email = tokenService.getEmailInfoByToken(token);
        System.out.println("邮箱地址：" + email + ";token为：" + token);
        return email;
    }
}
